import 'package:riverpod/riverpod.dart';
import '../../../core/state/page_state.dart';
import '../models/todo.dart';
import '../services/todo_service.dart';

class HomeState {
  final PageState pageState;
  final List<Todo> items;
  final String? error;

  const HomeState({
    this.pageState = PageState.idle,
    this.items = const [],
    this.error,
  });

  HomeState copyWith({PageState? pageState, List<Todo>? items, String? error}) => HomeState(
        pageState: pageState ?? this.pageState,
        items: items ?? this.items,
        error: error,
      );
}

class HomeVM extends StateNotifier<HomeState> {
  final TodoService service;
  HomeVM(this.service) : super(const HomeState());

  Future<void> load() async {
    state = state.copyWith(pageState: PageState.loading);
    try {
      final items = await service.getTodos();
      state = state.copyWith(
        items: items,
        pageState: items.isEmpty ? PageState.empty : PageState.success,
      );
    } catch (e) {
      state = state.copyWith(pageState: PageState.error, error: e.toString());
    }
  }
}